package com.kx.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kx.dao.QueryDao;
import com.kx.entity.Province;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class QueryProvinceServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //默认值，{}，表示json格式的数据
        String json = "{}";
        //获取请求参数，省份的id
        String strProid = request.getParameter("proid");
        //strProid.trim().length()>0表示去掉空格后长度大于0
        if (strProid != null && strProid.trim().length() > 0) {
            QueryDao dao = new QueryDao();
            Province p = dao.queryProvinceById(Integer.valueOf(strProid));
            //需要使用jackson把p对象转化为json
            ObjectMapper om = new ObjectMapper();
            json = om.writeValueAsString(p);
        }

        //把获取的数据，通过网络传给ajax中的异步对象，响应结果数据
        //指定服务器端(servlet)返回给浏览器的是json格式
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.println(json);
        pw.flush();
        pw.close();
    }
}
